<?php

namespace App\Actions;


use App\Dao\UserDao;
use App\Model\IncomeExpense;
use App\Model\Order;
use App\Model\User;
use App\Model\UserSuperVip;
use App\Model\UserVip;
use App\Services\PushMessageService;
use App\Utils\LoggerUtil;
use App\Utils\MemcacheClient;
use Hyperf\DbConnection\Db;

class PayAction
{
    public function __construct()
    {

    }


    /**
     * Note - 用户购买VIP/SVIP
     * DateTime 2024/8/23 18:57
     * User Admin
     * @param $orderInfo
     */
    public function updateUserVipInfo($orderInfo)
    {
        $now = time();
        $uid = $orderInfo['uid'];
        $userInfo = User::findUserInfoById($uid);

        $day = $orderInfo['goods'];
        $type = $orderInfo['consume_type'];
        $add_exp = intval(round($orderInfo['price']) * 100);

        //修改用户为vip用户
        if ($type >= 60) {
            //超级vip
            $userVipParams = array('noble' => '1', 'super_noble' => '1');
            // $userModel->update($uid, $userVipParams);
            User::query()->where('id', $uid)->update($userVipParams);
            $userVipParams["uid"] = $uid;
            LoggerUtil::write("update_user_svip", $userVipParams, 'update_user');

            // $free_video_time = !empty($setting->getOne('super_video_time')) ? intval($setting->getOne('super_video_time')) * 60 : 0;
            $free_video_time = 0;   // 新需求不送免费通话时长
            //写入tb_user_super_vip
            // $userVipModel = new UserVipModel();
            // $data = $userVipModel->find('*', 'uid = ? and status = ?', [$uid, 1], "", "tb_user_super_vip");
            $data = UserSuperVip::query()->where('uid', $uid)->where('status', 1)->first();
            $data = modelToArray($data);
            if (empty($data)) {
                $insertData['uid'] = $uid;
                $insertData['order_id'] = $orderInfo['order_id'];
                $insertData['type'] = $type;
                $insertData['day'] = $day;
                $insertData['ctime'] = $now;
                $insertData['status'] = 1;
                $insertData['etime'] = $now + 86400 * $day;
                $insertData['free_video_time'] = $free_video_time;
                // $userVipModel->insert($insertData, "tb_user_super_vip");
                UserSuperVip::query()->insert($insertData);

                // $user = UserDao::getInstance()->findUserInfoCache($uid);
                // $send_list = $userModel->message($user, 3, true);
                // if (!empty($send_list)) {
                //     Fun::socket_client('send', $user['id'], $user['session_id'], $send_list);
                // }
            } else {
                $insertData['order_id'] = $orderInfo['order_id'];
                $insertData['type'] = $type;
                $insertData['day'] = $day;
                $insertData['ctime'] = $now;
                $insertData['status'] = 1;
                $insertData['etime'] = $data['etime'] + 86400 * $day;
                $insertData['free_video_time'] = $free_video_time;
                // $userVipModel->update($data['id'], $insertData, "tb_user_super_vip");
                UserSuperVip::query()->where('id', $data['id'])->update($insertData);
            }
            LoggerUtil::write("update_user_svip", $insertData, 'insert_user_super_vip');
        } else {
            $userVipParams = array('noble' => '1');
            // $userModel->update($uid, $userVipParams);
            User::query()->where('id', $uid)->update($userVipParams);
            $userVipParams["uid"] = $uid;
            LoggerUtil::write("update_user_vip", $userVipParams, 'update_user');
            //写入tb_user_vip
            // $userVipModel = new UserVipModel();
            // $data = $userVipModel->find('*', 'uid = ? and status = ?', [$uid, 1]);
            $data = UserVip::query()->where('uid', $uid)->where('status', 1)->first();
            $data = modelToArray($data);
            if (empty($data)) {
                $insertData = [];
                $insertData['uid'] = $uid;
                $insertData['order_id'] = $orderInfo['order_id'];
                $insertData['type'] = $type;
                $insertData['day'] = $day;
                $insertData['ctime'] = $now;
                $insertData['status'] = 1;
                $insertData['etime'] = $now + 86400 * $day;
                // $userVipModel->insert($insertData);
                UserVip::query()->insert($insertData);

                // $user = UserDao::getInstance()->findUserInfoCache($uid);
                // $send_list = $userModel->message($user, 3);
                // if (!empty($send_list)) {
                //     Fun::socket_client('send', $user['id'], $user['session_id'], $send_list);
                // }

            } else {
                $insertData['uid'] = $uid;
                $insertData['order_id'] = $orderInfo['order_id'];
                $insertData['type'] = $type;
                $insertData['day'] = $day;
                $insertData['ctime'] = $now;
                $insertData['status'] = 1;
                $insertData['etime'] = $data['etime'] + 86400 * $day;
                // $userVipModel->update($data['id'], $insertData);
                UserVip::query()->where('id', $data['id'])->update($insertData);
            }
            LoggerUtil::write("update_user_vip", $insertData, 'insert_user_vip');
        }

        //购买vip送金币
        $add_count = 0;
        if (!empty($orderInfo['send_good'])) {
            $add_count = intval($orderInfo['send_good']);
        }
        if ($add_count > 0) {
            $giving_type = 1;
            $type = 5;//充值赠送
            $info['ext'] = '';
            $info['ext']->user_name = $userInfo['nickname'];
            $info['ext']->type = '充值';
            $info['ext']->orderid = $orderInfo['order_id'];
            $extend = json_encode($info['ext']);

            self::giving_GoldOrintegrate($userInfo, $extend, $giving_type, $add_count, $type);
        }
    }


    /**
     * Note - 用户购买金币
     * DateTime 2024/8/23 18:56
     * User Admin
     * @param $orderInfo
     * @return bool|void
     */
    public function userBuyGold($orderInfo)
    {
        $uid = $orderInfo['uid'];
        if ($orderInfo['consume_type'] < 50) {
            //购买金币
            $add_count = (int)$orderInfo['goods'];   //增加的金币数
            if ($add_count > 0) {
                // $userModel = new UserModel();
                $userInfo = User::findUserInfoById($orderInfo['uid']);
                $orderInfo['count_all'] = $userInfo['gift_count'] + $add_count;

                $currencyData['uid'] = $orderInfo['uid'];
                $currencyData['channel'] = $orderInfo['channel'];
                $currencyData['type'] = 1;
                $currencyData['sub_type'] = 1;
                $currencyData['amount'] = $orderInfo['goods'];
                $currencyData['account'] = $orderInfo['count_all'];
                $currencyData['ctime'] = time();
                $currencyData['from'] = (int)$orderInfo['from'];
                $currencyData['version_code'] = (int)$orderInfo['version_code'];
                $currencyData['package'] = $orderInfo['package'];
                $currencyData['ip'] = $orderInfo['ip'];
                // $rs1 = $userModel->insert($currencyData, 'tb_income_expense'); //插入流水表
                $rs1 = IncomeExpense::query()->insert($currencyData);//插入流水表
                LoggerUtil::write("user_buy_gold", $rs1);
                if ($rs1) {
                    $rs2 = UserDao::getInstance()->addUserGoldCount($uid, $add_count);  //更新用户余额
                } else {
                    $rs2 = false;
                }
                if ($orderInfo['consume_type'] == 10 && $orderInfo['version_code'] >= 125) {
                    // 125 以后版本首充赠送金币
                    $add_count = 30;
                    $type = 10; // 首充赠送
                    // (new OrderModel())->updateByWhereSet("send_good=send_good+{$add_count}", "id = {$orderInfo['id']}");
                    Order::query()->where('id', $orderInfo['id'])->update(['send_good' => DB::raw('send_good+' . $add_count)]);
                    $msg = json_encode(array('event' => 'first_recharge', 'msg' => ['uid' => $uid, 'pay_price' => $orderInfo['price']], 'desc' => 'success'));
                    // (new WyyClient())->putAttachMsgQueue(100000, $uid, $msg);
                    PushMessageService::putYunXinSendAttachMsgQueue(100000, $uid, $msg);
                } else {
                    // 购买金币送金币
                    $add_count = 0;
                    if (!empty($orderInfo['send_good'])) {
                        $add_count = intval($orderInfo['send_good']);
                    }
                    $type = 5;//充值赠送
                }

                if ($add_count > 0) {
                    $userInfo['gift_count'] = $orderInfo['count_all'];
                    $giving_type = 1;
                    // $type = 5;//充值赠送
                    $info['ext'] = '';
                    $info['ext']->user_name = $userInfo['nickname'];
                    $info['ext']->type = '充值';
                    $info['ext']->orderid = $orderInfo['order_id'];
                    $extend = json_encode($info['ext']);
                    self::giving_GoldOrintegrate($userInfo, $extend, $giving_type, $add_count, $type);
                }

                return $rs1 && $rs2;
            }
        }
    }

    /**
     * 赠送积分/金币
     * @param $to_userInfo -赠送用户
     * @param $extend -赠送原因
     * @param int $giving_type 赠送类型:1-金币 2-积分
     * @param int $bonus 赠送积分
     * @param int $type 科目 5充值赠送 20完成任务 35推广分成
     * @param int $user_id
     * @param string $guild
     */
    public function giving_GoldOrintegrate($to_userInfo, $extend, $giving_type = 1, $bonus = 0, $type = 5, $user_id = 0, $guild = '')
    {
        $to_uid = $to_userInfo['id'];
        if (in_array($giving_type, array(1, 2))) {
            $invite = $to_userInfo;
            $ext = '';
            if ($user_id) {
                // $userInfo = $userModel->find("id,package,channel,version_code", "id=?", [$user_id]);
                $userInfo = User::query()->select(['id', 'package', 'channel', 'version_code'])->where('id', $user_id)->first();
                $ext = json_encode(['p' => $userInfo['package'], 'v' => $userInfo['version_code'], 'c' => $userInfo['channel']]);
            }

            //插入流水表 - 收入
            $insertData = [];
            $insertData['uid'] = $to_uid;
            $insertData['user_id'] = $user_id;//系统赠送
            $insertData['ext'] = $ext;
            $insertData['amount'] = $bonus;
            $insertData['amount_type'] = $giving_type;
            if ($giving_type == 2) {
                $insertData['account'] = $bonus + $invite['integrate_usable_count'];
            } else {
                $insertData['account'] = $bonus + $invite['gift_count'];
            }
            $insertData['extend'] = $extend;
            $insertData['type'] = 1;// 1-收入 2-支出
            $insertData['sub_type'] = $type;
            $insertData['rate'] = ($to_userInfo['rate'] ?? 0) * 100;
            $insertData['ctime'] = time();
            $insertData['from'] = (int)$invite['from'];
            $insertData['version_code'] = (int)$invite['version_code'];
            $insertData['package'] = $invite['package'];
            $insertData['guild_num'] = $guild;
            IncomeExpense::query()->insert($insertData);
            // if (!$userModel->insert($insertData, 'tb_income_expense')) {
            // $userModel->rollBack();
            // Tool::log2("pay.txt", "insert tb_income_expense " . json_encode($insertData), 'invite');
            // }

            //修改用户金币/积分
            if ($giving_type == 2) {
                //修改用户积分
                if (!UserDao::getInstance()->addAnchorAccount($invite['id'], $bonus)) {
                    // $userModel->rollBack();
                    // Tool::log2("pay.txt", "insert tb_user " . $invite['id'] . ":" . $bonus, 'invite');
                }
            } else {
                //修改用户金币
                // 任务领取的金币计入系统赠送
                if ($type == 20 && $invite['version_code'] >= 125) {
                    // $userModel->updateByWhereSet("sys_send_count=sys_send_count+{$bonus}", "id={$invite['id']}");
                    User::query()->where('id', $invite['id'])->update(['sys_send_count' => DB::raw('sys_send_count+' . $bonus)]);
                } elseif (in_array($type, [5, 10]) && $invite['version_code'] >= 125) {
                    // 充值赠送的金币计入充值赠送
                    // $userModel->updateByWhereSet("recharge_send_count=recharge_send_count+{$bonus}", "id={$invite['id']}");
                    User::query()->where('id', $invite['id'])->update(['recharge_send_count' => DB::raw('recharge_send_count+' . $bonus)]);
                } else {
                    UserDao::getInstance()->addUserGoldCount($invite['id'], $bonus);
                }

                // if (!$userModel->addUserGoldCount($invite['id'], $bonus)) {//修改用户礼物数量
                //     // $userModel->rollBack();
                //     // Tool::log2("pay.txt", "insert tb_user " . $invite['id'] . ":" . $bonus, 'invite');
                // }
            }
            // $userModel->commit();

            MemcacheClient::getInstance()->delete("userInfo_" . $invite['id']);
            MemcacheClient::getInstance()->delete('user_income_expense_invite_' . $invite['id']);
        }
    }

    /**
     * 赠送VIP
     * @param $to_userInfo -赠送用户信息
     * @param $days -赠送天数
     * @param $giving_type -赠送类型:1-VIP；2-SVIP
     * @param $type -VIP类型:55-VIP福利；65-SVIP福利
     */
    public function giving_vip($to_userInfo, $giving_type, $days, $type)
    {
        $to_uid = $to_userInfo['id'];
        if (in_array($giving_type, array(1, 2))) {
            $userModel = new UserModel();
            $userVipParams = array('noble' => '1');
            if ($giving_type == 2) {
                $userSVipModel = new UserVipModel();
                $data = $userSVipModel->find('*', 'uid = ? and status = ?', [$to_uid, 1], "", "tb_user_super_vip");
                if (empty($data)) {
                    $insertData['uid'] = $to_uid;
                    $insertData['order_id'] = 0;
                    $insertData['type'] = $type;
                    $insertData['day'] = $days;
                    $insertData['ctime'] = time();
                    $insertData['status'] = 1;
                    $insertData['etime'] = time() + 86400 * $days;
                    $insertData['free_video_time'] = 0;
                    $userSVipModel->insert($insertData, "tb_user_super_vip");
                } else {
                    $insertData['order_id'] = 0;
                    $insertData['day'] = $days;
                    $insertData['status'] = 1;
                    $insertData['etime'] = $data['etime'] + 86400 * $days;
                    $insertData['free_video_time'] = 0;
                    $userSVipModel->update($data['id'], $insertData, "tb_user_super_vip");
                }
                $userVipParams = array('noble' => '1', 'super_noble' => '1');

                Tool::log2("send_user_svip.txt", $insertData, 'insert_user_super_vip');

                // Mem::delete("userInfo_" . $to_uid);
            } else {
                $userVipModel = new UserVipModel();
                $data = $userVipModel->find('*', 'uid = ? and status = ?', [$to_uid, 1], "", "tb_user_vip");
                if (empty($data)) {
                    $insertData['uid'] = $to_uid;
                    $insertData['order_id'] = 0;
                    $insertData['type'] = $type;
                    $insertData['day'] = $days;
                    $insertData['ctime'] = time();
                    $insertData['status'] = 1;
                    $insertData['etime'] = time() + 86400 * $days;
                    // $insertData['free_video_time'] = 0;
                    $userVipModel->insert($insertData, "tb_user_vip");
                } else {
                    $insertData['order_id'] = 0;
                    $insertData['day'] = $days;
                    $insertData['status'] = 1;
                    $insertData['etime'] = $data['etime'] + 86400 * $days;
                    // $insertData['free_video_time'] = 0;
                    $userVipModel->update($data['id'], $insertData, "tb_user_vip");
                }
                Tool::log2("send_user_vip.txt", $insertData, 'insert_user_vip');

                // Mem::delete("userInfo_" . $to_uid);
            }
            //更改用户vip属性
            $userModel->update($to_uid, $userVipParams);
        }
    }

    // 订单更新用户聊币 - 取消
    public function userBuyChatCoin($order_info)
    {
        $user_model = new UserModel();

        $user_chat_coin = $user_model->find('*', 'uid = ?', [$order_info['uid']], '', 'tb_user_chat_coin');
        if (empty($user_chat_coin)) {
            $chat_coin = 0;
        } else {
            $chat_coin = $user_chat_coin['chat_coin'];
        }
        $user_model->execute('insert into tb_user_chat_coin (uid, chat_coin, utime) values (?, ?, ?) on duplicate key update chat_coin = chat_coin + values(chat_coin), utime = values(utime)', [$order_info['uid'], $order_info['goods'], time()]);

        $chat_coin_account = $chat_coin + $order_info['goods'];
        // 添加记录
        $record = [
            'uid' => $order_info['uid'],
            'type' => 1,
            'sub_type' => 1,
            'amount' => $order_info['goods'],
            'account' => $chat_coin_account,
            'ctime' => time(),
            'from' => $order_info['from'],
            'ip' => $order_info['ip'],
            'version_code' => $order_info['version_code'],
            'channel' => $order_info['channel'],
        ];
        $user_model->insert($record, 'tb_chat_coin_record');

        // 是否需要添加金币和金币记录
        if ($order_info['send_good'] > 0) {
            $user_info = $user_model->findUserInfoById($order_info['uid']);
            $user_model->execute('update tb_user set gift_count = gift_count + ? where id = ?', [$order_info['send_good'], $user_info['id']]);

            $chat_coin_account = $user_info['gift_count'] + $order_info['send_good'];

            $record = [
                'uid' => $user_info['id'],
                'type' => 1,
                'sub_type' => 63, // 购买聊币赠送金币
                'amount_type' => 1, //金币
                'amount' => $order_info['send_good'],
                'account' => $chat_coin_account,
                'ctime' => time(),
                'from' => $order_info['from'],
                'ip' => $order_info['ip'],
                'version_code' => $order_info['version_code'],
                'channel' => $order_info['channel'],
            ];
            $user_model->insert($record, 'tb_income_expense');
        }
    }

    // 赠送聊币 - 取消
    public function updateUserChatCoin($order_info)
    {
        $user_model = new UserModel();

        $user_chat_coin = $user_model->find('*', 'uid = ?', [$order_info['uid']], '', 'tb_user_chat_coin');
        if (empty($user_chat_coin)) {
            $chat_coin = 0;
        } else {
            $chat_coin = $user_chat_coin['chat_coin'];
        }
        $user_model->execute('insert into tb_user_chat_coin (uid, chat_coin, utime) values (?, ?, ?) on duplicate key update chat_coin = chat_coin + values(chat_coin), utime = values(utime)', [$order_info['uid'], $order_info['send_chat_coin'], time()]);

        $chat_coin_account = $chat_coin + $order_info['send_chat_coin'];
        // 添加记录
        $record = [
            'uid' => $order_info['uid'],
            'type' => 1,
            'sub_type' => 2,
            'amount' => $order_info['send_chat_coin'],
            'account' => $chat_coin_account,
            'ctime' => time(),
            'from' => $order_info['from'],
            'ip' => $order_info['ip'],
            'version_code' => $order_info['version_code'],
            'channel' => $order_info['channel'],
        ];
        $user_model->insert($record, 'tb_chat_coin_record');
    }


    /**
     * 用户是否是首次充值判断
     * @param $orderInfo
     * @return bool
     */
    public function checkFirstRecharge($orderInfo)
    {
        $uid = $orderInfo['uid'];
        $isFirstRecharge = false;
        if ($orderInfo['consume_type'] < 50 && $orderInfo['goods'] > 0) {
            $userModel = new UserModel();
            $userInfo = $userModel->findUserInfoById($orderInfo['uid']);

            // 用户首次充值获得三次免费速聊
            // if(in_array($orderInfo['consume_type'],[7,8,9,10]) && $orderInfo['order_from_type']==8){
            //     $freeCountModel=new CallFreeCountModel();
            //     $freeCountModel->firstRechargeGetCount($uid,$userInfo);
            // }


            // 是否首次充值
            $orderModel = new OrderModel();
            $orderCount = $orderModel->findTotal("id", "order_id != {$orderInfo['order_id']} and uid={$uid} and consume_type<50 and consume_type>5 and pay_status=1 and notify_status=1", []);

            if (!$orderCount) {
                $isFirstRecharge = true;
                $orderModel->updateByWhere(['is_first_recharge' => 1], "order_id = '{$orderInfo['order_id']}'");
            }


            // 是否有上级推广用户
            $inviteUser = $userModel->findUserInfoById($userInfo['inviteUid']);
            if (empty($inviteUser)) {
                return $isFirstRecharge;
            }

            // 上级为女性用户，提成每次充值的20%
            // if ($inviteUser['sex'] == 2) {
            $rate = PAY_WOMEN_MEN_RATE;

            // 2022-11-17调整为25%
            // $rate=0.25;

            // // 9月24-10月31 活动期间 提成30%
            // $time=time();
            // if( $time >= strtotime("2022-09-24 00:00:00") && $time <= strtotime("2022-10-31 23:59:59") ){
            //     $rate=0.3;
            // }

            // 获取主播提成比例
            $inviteUser['rate'] = (new AnchorModel())->getValue($userInfo['inviteUid'], 'rate');

            // 可获得积分
            // $integral = intval($orderInfo['goods'] * $rate);
            $integral = intval($orderInfo['price'] * 10 * $rate);

            $info['ext'] = '';
            $info['ext']->user_name = $userInfo['nickname'];
            $info['ext']->type = '充值' . $orderInfo['price'] . "元";
            $info['ext']->orderid = 0;
            $info['ext']->earnings = $integral . " 积分";
            $extend = json_encode($info['ext']);
            $this->giving_GoldOrintegrate($inviteUser, $extend, 2, $integral, 35, $orderInfo['uid'], $inviteUser['guild_num'] ?? '');
            // }


            if ($orderCount > 0) {
                return $isFirstRecharge;
            }

            // // 用户首次充值权益 2022/12/27取消赠送积分、金币、会员
            // // 上级为女性用户
            // if ($inviteUser['sex'] == 2) {
            //     //赠送30积分
            //     $info['ext'] = '';
            //     $info['ext']->user_name = $userInfo['nickname '];
            //     $info['ext']->type = '首次充值' . $orderInfo['price'] . "元";
            //     $info['ext']->orderid = 0;
            //     $info['ext']->earnings = 50 ." 积分";
            //     $extend = json_encode($info['ext']);
            //     $this->giving_GoldOrintegrate($inviteUser, $extend, 2, 50, 35,$orderInfo['uid']);
            //
            // } else {
            //     // 上级为男用户
            //     // 赠送3天svip
            //     $this->giving_vip($inviteUser, 2, 3, 55);
            //
            //     //赠送50金币
            //     $info['ext'] = '';
            //     $info['ext']->user_name = $userInfo['nickname'];
            //     $info['ext']->type = '充值' . $orderInfo['price'] . "元";
            //     $info['ext']->orderid = 0;
            //     $info['ext']->earnings = 50 ." 金币";
            //     $extend = json_encode($info['ext']);
            //     $this->giving_GoldOrintegrate($inviteUser, $extend, 1, 50, 35,$orderInfo['uid']);
            // }
        }

        return $isFirstRecharge;
    }
}